/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.item

import org.ibiblio.terasaur.controller.ParamsHelper
import org.ibiblio.terasaur.item.SearchService

class SearchController {
    def searchService // injected
    static defaultAction = "list"
    static ParamsHelper _paramsHelper = new ParamsHelper()

    def list = {
        if (!params.query) {
            redirect(controller:"browse", action: "recent")
            return
        }

        def searchParams = _paramsHelper.getOffsetMax(params)
        searchParams.query = params.query
        def result = searchService.query(searchParams)
        if (result.error) {
            flash.message = message(code:result.error)
        }

        def label = message(code:'item.search.results.label', args:[result.query])
        Map map = [
            pageTitle: label,
            listLabel: label,
            itemListType: 'solr',
            searchQueryText: result.query,
            error: (result.error) ? true : false,
            paginationParams: [query: params.query]
        ]

        if (result.itemList) {
            map.itemList = result.itemList
            map.itemListTotal = result.documentList.numFound
        } else {
            map.itemList = []
            map.itemListTotal = 0
        }

        render(view:"/item/list", model:map)
    }

}
